import { defineStore } from 'pinia'
import { io, Socket } from 'socket.io-client'
import { useUserStore } from './useUser'
import { v4 as uuidv4 } from 'uuid'
import { useRoute } from "vue-router";
import { useRouter } from 'nuxt/app';
import { ElNotification } from 'element-plus';
import { useRuntimeConfig } from '#app'


interface MessageItem {
    content: string,
    contentType: number,
    from: string,
    fromAvatar: string,
    fromName: string,
    fromType: string,
    time: Number,
    to: string,
    toAvatar: string,
    toName: string,
    toType: string,
    id: string
}

export const useSocketStore = defineStore('socket', {
    state: () => ({
        socket: null as Socket | null,
        isConnected: false,
        talkList: [],
        messages: {} as Record<string, MessageItem[]>,
        currentImKey: "",
        viewGoodsInfo: {},
        noReadMsgNum: 0,
        msgAudio: false,
        noReadMsgKeys: {},
    }),

    getters: {
        getTalkList: (state) => state.talkList,
        getCurrentImKey: (state) => state.currentImKey,
        getMessages: (state) => state.messages,
        getCurrentTalk: (state) => {
            return state.talkList.find((item: any) => item.imKey === state.currentImKey)
        },
        getViewGoodsInfo: (state) => state.viewGoodsInfo,
        getCurrentMsgList: (state) => state.messages[state.currentImKey] || [],
        getMsgAudioStatus: (state) => state.msgAudio,
        getTalkNoReadMsgNum: (state) => (user: string) => {
            const keys = Object.keys(state.noReadMsgKeys)
            if (keys.length === 0) {
                // 在 SSR 环境下安全地获取 noReadMsgKeys
                if (process.client) {
                    const noReadMsgKeys = localStorage.getItem('noReadMsgKeys')
                    if (noReadMsgKeys) {
                        state.noReadMsgKeys = JSON.parse(noReadMsgKeys)
                    }
                }
            }
            return state.noReadMsgKeys[user] || 0
        }
    },
    actions: {
        setOnlineStatus(data) {
            for (let i = 0; i < data.length; i++) {
                const item = data[i]
                const talkIndex = this.talkList.findIndex(talkItem => talkItem.imKey === item.user)
                if (talkIndex !== -1) {
                    this.talkList[talkIndex].online = item.online
                }
            }
        },
        setMsgAudio(status) {
            this.msgAudio = status
        },
        setNoReadMsgNum(num) {
            this.noReadMsgNum = num
            // 播放消息提示音
            this.setMsgAudio(true)
            setTimeout(() => {
                this.setMsgAudio(false)
            }, 1000)
        },
        setTlakItemNoReadNum(msgData) {
            console.log(msgData.user)
            const userNum = this.noReadMsgKeys[msgData.user] || 0
            this.noReadMsgKeys[msgData.user] = userNum + 1
            if (process.client) {
                localStorage.setItem('noReadMsgKeys', JSON.stringify(this.noReadMsgKeys))
            }
            // 播放消息提示音
            this.setMsgAudio(true)
            setTimeout(() => {
                this.setMsgAudio(false)
            }, 1000)
        },
        setMsgListRead() {
            if (!this.currentImKey) return
            this.messages[this.currentImKey] = this.messages[this.currentImKey].map(item => {
                item.read = true
                return item
            })
        },
        setAppointMsgRead(from, msgKeys = []) {
            if (!from || !msgKeys || !msgKeys.length) return
            for (let i = 0; i < this.messages[from].length; i++) {
                const item = this.messages[from][i]
                if (msgKeys.includes(item.msgKey)) {
                    this.messages[from][i].read = true
                }
            }
        },
        setViewGoodsInfo(info: any) {
            this.viewGoodsInfo = info
        },
        clearMessages() {
            this.messages = {}
        },
        setTalkList(list: any) {
            this.talkList = list
        },
        setCurrentImKey(key: string) {
            this.currentImKey = key
            // 重置当前用户的未读数量
            this.noReadMsgKeys[key] = 0
            if (process.client) {
                localStorage.setItem('noReadMsgKeys', JSON.stringify(this.noReadMsgKeys))
            }
        },
        initSocket() {
            // 防止重复连接
            if (this.isConnected || this.socket) {
                return
            }

            // 初始化连接逻辑
            try {
                const userStore = useUserStore()
                const runtimeConfig = useRuntimeConfig()
                this.socket = io(runtimeConfig.public.socketBase, {
                    query: {
                        imKey: userStore.getUserInfo.uimKey
                    },
                    reconnection: true, // 启用重连
                    reconnectionAttempts: 20, // 重连尝试次数
                    reconnectionDelay: 10000, // 重连延迟时间
                })

                this.setupSocketListeners()
            } catch (error) {
                console.error('Socket connection failed:', error)
            }
        },
        setupSocketListeners() {
            if (!this.socket) return
            this.socket.on('connect', () => {
                this.isConnected = true
                console.log('Socket connected')
                this.socket.emit("chatList", {}, (res) => {
                    if (res.code === 200) {
                        this.setTalkList(res.data);
                    }
                });
            })
            this.socket.on('disconnect', () => {
                this.isConnected = false
                console.log('Socket disconnected')
            })
            this.socket.on('error', (error) => {
                console.error('Socket error:', error)
            })
            this.socket.on('chatMsg', (res) => {
                console.log('chatMsg msg:', res)
                const route = useRouter()
                // 获取当前路由地址
                const currentPath = route.currentRoute.value.path
                if (currentPath !== '/chat') {
                    ElNotification.info({
                        title: `${res.data.msg.fromName}`,
                        message: this.lastMsg(res.data.msg),
                        onClick: () => {
                            route.push('/chat')
                        }
                    })
                    const nums = this.noReadMsgNum + 1
                    this.setNoReadMsgNum(nums)
                }
                // 如果当前imKey不等于消息来源imKey，声音提醒，并更新未读消息数量
                if (this.currentImKey !== res.data.user) {
                    this.setTlakItemNoReadNum(res.data)
                }
                this.addMessage(res.data.msg.from, res.data.msg)
                this.setTalkListLastMsg(res.data.msg, 2)
            })
            this.socket.on('setRead', (res) => {
                console.log('setRead res:', res)
                this.setAppointMsgRead(res.from, res.msgKeys)
            })
        },
        setTalkListLastMsg(msg, type = 1) { // type 1: 自己发的 ， 2 收到的
            const imgKey = type == 1 ? msg.to : msg.user
            console.log('setTalkListLastMsg imgKey:', imgKey)
            const findIndex = this.talkList.findIndex((item: any) => item.user === imgKey || item.toUser === imgKey)
            console.log('setTalkListLastMsg findIndex:', findIndex)
            if (findIndex !== -1) {
                console.log('msg:', msg)
                const lastItem = this.talkList[findIndex]
                lastItem.lastMessage = msg.msg || msg
                lastItem.updateTime = Date.now()
                this.talkList[findIndex] = lastItem
            }
        },
        disconnect() {
            if (this.socket) {
                this.socket.disconnect()
                this.socket = null
                this.isConnected = false
            }
        },

        // 获取在线状态方法
        getOnlineStatus(imKey: string, callback: (res: any) => void) {
            this.socket.emit("userOnline", [imKey], callback);
        },

        // 发送消息的方法
        sendMessage(event: string, data: any, callback: (res: any) => void, send = true) {
            console.log(event, data)
            if (!this.getCurrentImKey) return
            if (this.socket && this.isConnected) {
                const msgKey = uuidv4()
                data.msgKey = msgKey
                if (send) {
                    const cloneData = JSON.parse(JSON.stringify(data));
                    if (cloneData.toServiceImKey) {
                        cloneData.to = cloneData.toServiceImKey;
                        delete cloneData.toServiceImKey;
                    }
                    this.socket.emit(event, cloneData, callback)
                }
                const userStore = useUserStore()
                const msgData = {
                    from: userStore.getUserInfo.uimKey,
                    fromName: userStore.getUserInfo.nickName || userStore.getUserInfo.phonenumber,
                    fromAvatar: userStore.getUserInfo.avatar || '',
                    fromType: 1,
                    to: data.to,
                    toName: '',
                    toAvatar: '',
                    toType: 2,
                    content: data.content,
                    contentType: data.contentType,
                    time: Date.now(),
                    msgKey,
                    read: false,
                    exData: data.exData || {}
                }
                console.log('msgData:', msgData)
                this.addMessage(data.to, msgData)
                this.setTalkListLastMsg(msgData, 1)
            }
        },

        // 添加消息
        // 添加其他全局事件监听
        addMessage(imgKey: string, message: any) {
            try {
                if (!this.messages[imgKey]) {
                    this.messages[imgKey] = []
                    this.socket.emit("chatList", {}, (res) => {
                        if (res.code === 200) {
                            this.setTalkList(res.data);
                        }
                    });
                }
                if (Array.isArray(message)) {
                    for (let i = 0; i < message.length; i++) {
                        const item = message[i]
                        // 去重
                        if (!this.messages[imgKey].find((msg: MessageItem) => msg.msgKey === item.msg.msgKey)) {
                            this.messages[imgKey].unshift(item.msg)
                        }
                    }
                } else {
                    // 去重
                    if (!this.messages[imgKey].find((msg: MessageItem) => msg.msgKey === message.msgKey)) {
                        this.messages[imgKey].push(message)
                    }
                }
            } catch (error) {
                console.error('add message error:', error.message)
            }
        },
        // 获取消息内容，非文字内容返回[图片]、[视频]、[文件]等类型
        lastMsg(msg) {
            if (!msg) {
                return "--";
            }
            const contentType = msg.contentType;
            if (contentType === 1) {
                return msg.content;
            }
            if (contentType === 2) {
                return "[图片]";
            }
            if (contentType === 4) {
                //return '新提示消息';
            }
            if (contentType === 5) {
                return "[视频]";
            }
            if (contentType === 6) {
                return "[文件]";
            }
            if (contentType === 7) {
                return "[加价申请]";
            }
            if (contentType === 8) {
                return "[分享服务]";
            }
            if (contentType === 10) {
                return "[邀请支付]";
            }
            return "";
        },
    }
})